package servlet;

import model.Goods;
import model.Order;
import util.JDBCUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/OrderAllServlet.do")
public class OrderAllServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        List<Order> searchResults3 = allQuery();

        HttpSession session = request.getSession();
        session.setAttribute("searchResults3", searchResults3);

        response.sendRedirect(request.getContextPath() + "/background1/admin/orderManager.jsp");
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    private List<Order> allQuery() {
        String SQL = "SELECT * FROM `order`";

        List<Order> orderList = new ArrayList<>();
        JDBCUtil jdbcUtil = new JDBCUtil();
        ResultSet resultSet = null;

        try {
            resultSet = jdbcUtil.prepareQuery(SQL);

            while (resultSet != null && resultSet.next()) {
                int orderId = resultSet.getInt("order_id");
                int userId = resultSet.getInt("user_id");
                String recipientName = resultSet.getString("recipient_name");
                String recipientAddress = resultSet.getString("recipient_address");
                String recipientPhone = resultSet.getString("recipient_phone"); // Changed to String
                String notes = resultSet.getString("notes");
                String orderDate = resultSet.getString("order_date");
                String orderStatus = resultSet.getString("order_status");
                double orderTotal = resultSet.getDouble("order_total");

                Order order = new Order(orderId, userId, recipientName, recipientAddress, recipientPhone,
                        notes, orderStatus, orderDate, orderTotal);
                orderList.add(order);
            }
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException("Error querying the database", e);
        } finally {
            try {
                if (resultSet != null) resultSet.close();
                jdbcUtil.closeConnection();
            } catch (SQLException e) {
                e.printStackTrace();
                // Optionally log the exception here
            }
        }

        return orderList;
    }
}
